import json

from django.contrib.auth import login, update_session_auth_hash, logout

from django.http import JsonResponse
from django.shortcuts import render, get_object_or_404

from django.views.decorators.csrf import csrf_exempt

from djangoProject.views import r
from user.forms import LoginForm, UserInfoForm, PasswordChangeForm, UserAddForm
from user.models import User


def find_by_id(request):
    user_id = request.GET.get('id')
    user = get_object_or_404(User, id=user_id)
    return render(request, 'user-update.html', {'user': user})


def update_user(request):
    if request.method == 'POST':
        user_id = request.POST.get('id')
        user = get_object_or_404(User, id=user_id)
        user.real_name = request.POST.get('real_name')
        user.phone = request.POST.get('phone')
        user.email = request.POST.get('email')
        user.sex = request.POST.get('sex')
        user.role = request.POST.get('role')
        user.status = request.POST.get('status')
        user.update_by = request.user.username  # 假设当前登录用户为更新者
        user.save()
        return JsonResponse({'code': 200, 'message': '用户信息更新成功'})
    else:
        return JsonResponse({'code': 400, 'message': '请求方法错误'})

@csrf_exempt
def user_delete(request, user_id):
    try:
        user = User.objects.get(id=user_id)
        user.delete()
        return JsonResponse({'code': 200, 'message': '删除成功'})
    except User.DoesNotExist:
        return JsonResponse({'code': 404, 'message': '用户不存在'})


def user_list(request):
    users = User.objects.all()
    return render(request, 'user-list.html', {'users': users})


def user_add(request):
    if request.method == 'POST':
        form = UserAddForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.password = form.cleaned_data['password']
            current_user_info = json.loads(r.get('currentUser'))
            user.create_by = current_user_info['username']
            user.update_by = current_user_info['username']
            user.save()
            return JsonResponse({'code': '200', 'message': '添加成功'})
        else:
            return JsonResponse({'code': '400', 'errors': form.errors})

    else:
        form = UserAddForm()

    return render(request, 'user-add.html', {'form': form})


def change_password(request):
    user_info_str = r.get('currentUser')
    if not user_info_str:
        return JsonResponse({'code': 400, 'message': '用户未登录'})

    user_info = json.loads(user_info_str)
    user_id = user_info.get('id')
    print(user_id)
    try:
        user = User.objects.get(id=user_id)
    except User.DoesNotExist:
        return JsonResponse({'code': 400, 'message': '用户不存在'})

    if request.method == 'POST':
        form = PasswordChangeForm(request.POST)
        if form.is_valid():
            old_password = form.cleaned_data.get('old_password')
            new_password = form.cleaned_data.get('new_password1')
            if old_password != user.password:
                return JsonResponse({'code': 400, 'message': '原始密码不正确'})
            user.password = new_password
            user.save()
            # 更新Redis中的用户信息
            user_info['password'] = user.password
            r.set('currentUser', json.dumps(user_info))
            return JsonResponse({'code': 200, 'message': '密码修改成功'})
        else:
            return JsonResponse({'code': 400, 'errors': form.errors})
    else:
        form = PasswordChangeForm()

    return render(request, 'user-password.html', {'form': form})


def user_info(request):
    # 从Redis中获取当前用户信息
    user_info_str = r.get('currentUser')
    if user_info_str:
        user_info = json.loads(user_info_str)
    else:
        user_info = {}

    if request.method == 'POST':
        form = UserInfoForm(request.POST, initial=user_info)
        if form.is_valid():
            updated_user_info = {
                'username': form.cleaned_data.get('username'),
                'email': form.cleaned_data.get('email'),
                'real_name': form.cleaned_data.get('real_name'),
                'phone': form.cleaned_data.get('phone'),
                'sex': form.cleaned_data.get('sex'),
                'id': form.cleaned_data.get('id')
            }
            r.set('currentUser', json.dumps(updated_user_info))
            user = User.objects.get(id=user_info['id'])
            user.email = updated_user_info['email']
            user.real_name = updated_user_info['real_name']
            user.phone = updated_user_info['phone']
            user.sex = updated_user_info['sex']
            user.save()
            return JsonResponse({'code': 200, 'message': '个人信息已成功更新！'})
        else:
            return JsonResponse({'code': 400, 'message': '表单数据无效！'})
    else:
        form = UserInfoForm(initial=user_info)

    context = {
        'form': form,
    }
    return render(request, 'user-info.html', context)


@csrf_exempt
def user_login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            try:
                user = User.objects.get(username=username)
                if password == user.password:
                    islogin = login(request, user)
                    print(islogin)
                    # 将用户信息存储到Redis中
                    user_info = {
                        'username': user.username,
                        'email': user.email,
                        'real_name': user.real_name,
                        'phone': user.phone,
                        'sex': user.sex,
                        'id': user.id
                    }
                    request.session['currentUser'] = user_info;
                    r.set(f'currentUser', json.dumps(user_info))
                    return JsonResponse({'code': 200, 'message': '登录成功'})
                else:
                    return JsonResponse({'code': 400, 'message': '用户名或密码错误'})
            except User.DoesNotExist:
                return JsonResponse({'code': 400, 'message': '用户名或密码错误'})
        else:
            return JsonResponse({'code': 400, 'message': '表单无效'})
    else:
        form = LoginForm()
    return render(request, 'login.html', {'form': form})


def user_logout(request):
    logout(request)

    # 清除 session 中的用户信息
    if 'currentUser' in request.session:
        del request.session['currentUser']

    # 清除 Redis 中的用户信息
    r.delete('currentUser')

    form = LoginForm()
    return render(request, 'login.html', {'form': form})